package com.budwk.app.waterquality.services.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.utils.PoiUtil;
import com.budwk.app.utils.StrUtil;
import com.budwk.app.waterquality.component.CommonComponent;
import com.budwk.app.waterquality.config.AppException;
import com.budwk.app.waterquality.models.AppealRecord;
import com.budwk.app.waterquality.models.WaterQualityIndicator;
import com.budwk.app.waterquality.services.AppealrecordService;
import com.budwk.app.waterquality.vo.AppealRecordQueryVo;
import com.budwk.app.waterquality.vo.ParamProblemVo;
import com.budwk.app.waterquality.vo.WaterQualityVo;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.database.service.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

@IocBean(args = {"refer:dao"})
@Slf4j
public class AppealrecordServiceImpl extends BaseServiceImpl<AppealRecord> implements AppealrecordService {
    public AppealrecordServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public void saveAbnormalMarking(WaterQualityIndicator indicator, ParamProblemVo p) {
        Sys_user user = CommonComponent.getCurrentUser();
        WaterQualityVo w = JSONObject.parseObject(indicator.getWaterQualityData(), WaterQualityVo.class);
        AppealRecord a = new AppealRecord();
        Sys_unit unit = user.getUnit();
        a.setSTCD(w.getSTCD())
                .setSTNM(w.getSTNM())
                .setLYNM(w.getLYNM())
                .setSPT(w.getSPT())
                .setFXT(w.getFXT())
                .setExceptionData(JSONObject.toJSONString(p))
                .setCreateId(user.getId())
                .setCreateDate(LocalDateTime.now())
                .setUpdateId(user.getId())
                .setUpdateDate(LocalDateTime.now())
                .setUnitName(unit != null ? unit.getName() : user.getImportUnitName())
                .setUnitId(unit != null ? user.getUnitId() : null);
        //
        a.setCheckDate(LocalDateTime.now()).setCheckText("已检查，审核通过").setCheckName("李小雪");
        a.setOperateDate(LocalDateTime.now()).setOperateText("经检查，审批通过").setOperaterName("李思思");
        a.setHandleOperate("修改").setUpdateValue("10.24");
        this.insert(a);
    }

    @Override
    public Pagination listByPage(AppealRecordQueryVo queryVo) {
        Cnd cnd = buildQueryCondition(queryVo);
        return listPage(queryVo.getPageNo(), queryVo.getPageSize(), cnd);
    }

    private Cnd buildQueryCondition(AppealRecordQueryVo queryVo) {
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        if (StringUtils.isNotEmpty(queryVo.getUnitName())) {
            where.andEquals(AppealRecord::getUnitName, queryVo.getUnitName());
        }
        if (StringUtils.isNotEmpty(queryVo.getStnm())) {
            where.andEquals(AppealRecord::getSTNM, queryVo.getStnm());
        }
        if (StringUtils.isNotEmpty(queryVo.getYpty())) {
            where.andEquals(AppealRecord::getYpty, queryVo.getYpty());
        }
        if (StringUtils.isNotEmpty(queryVo.getIsAppeal())) {
            where.andEquals(AppealRecord::getIsAppeal, queryVo.getIsAppeal());
        }
        if (StringUtils.isNotEmpty(queryVo.getSpt())) {
            String[] split = queryVo.getSpt().split(",");
            String start = split[0] + " 00:00:00";
            String end = split[1] + " 23:59:59";
            where.andBetween("water_quality_data->>'SPT'", start, end);
        }
        return cnd;
    }

    @Override
    public String downloadAppealLedger(AppealRecordQueryVo queryVo, HttpServletResponse response) {
        try {
            // 获取查询数据
            Cnd cnd = buildQueryCondition(queryVo);
            List<AppealRecord> list = this.query(cnd);
            // 获取模板导出
            XSSFWorkbook workbook = new XSSFWorkbook(PoiUtil.getInputStream("/formTemplate/file/appealRecord/appealRecordLedger.xlsx"));
            SXSSFWorkbook book = new SXSSFWorkbook(workbook, 100);
            if (CollectionUtil.isEmpty(list)) {
                String downFileUrl = PoiUtil.getDownFileUrl(System.currentTimeMillis() + ".xlsx", book, response);
                return downFileUrl;
            }
            SXSSFSheet sheet = book.getSheetAt(0);
            int rowIndex = 2;
            for (AppealRecord a : list) {
                String exceptionData = a.getExceptionData();
                ParamProblemVo p = JSONObject.parseObject(exceptionData, ParamProblemVo.class);
                List<String> datas = List.of(String.valueOf(rowIndex-1), StrUtil.formatStr(a.getSTCD()), StrUtil.formatStr(a.getSTNM()),
                        StrUtil.formatStr(a.getLYNM()), "", StrUtil.formatStr(a.getSPT()), StrUtil.formatStr(a.getFXT()),
                        StrUtil.formatStr(p.getField()), StrUtil.formatStr(p.getFieldUnit()), StrUtil.formatStr(p.getValue()));
                SXSSFRow row = sheet.createRow(rowIndex);
                int cellIndex = 0;
                for (String data : datas) {
                    SXSSFCell cell = row.createCell(cellIndex);
                    cell.setCellValue(data);
                    cellIndex ++;
                }
                rowIndex ++;
            }
            book.setCompressTempFiles(true);

            String downFileUrl = PoiUtil.getDownFileUrl(System.currentTimeMillis() + ".xlsx", book, response);
            return downFileUrl;
        } catch (Exception e) {
            log.error("error:", e);
            throw new AppException("下载异常！");
        }
    }
}
